package com.slipper.sfts.websocket;

import com.slipper.common.util.StringUtil;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class WebsocketManager {
    private static final Logger logger = LoggerFactory.getLogger(WebsocketManager.class);
    private static final ConcurrentHashMap<String, List<WebSocketSession>> sessionPool = new ConcurrentHashMap<>();

    public static void addSession(String memberId, WebSocketSession session) {
        if (StringUtil.isBlank(memberId)) return;

        List<WebSocketSession> sessionList = sessionPool.computeIfAbsent(memberId, list -> new ArrayList<>());
        sessionList.add(session);
        int size = 0;
        for (List<WebSocketSession> list : sessionPool.values()) {
            size += list.size();
        }
        logger.info("当前在线人数：{}", size);
    }

    public static void closeSession(WebSocketSession session) {
        String memberId = session.getAttributes().get("memberId").toString();
        if (StringUtil.isBlank(memberId) || !sessionPool.containsKey(memberId)) return;

        try {
            List<WebSocketSession> sessionList = sessionPool.get(memberId);
            if (!sessionList.isEmpty()) {
                WebSocketSession currSession = sessionList.stream()
                        .filter(item -> session.getId().equals(item.getId()))
                        .findFirst().orElse(null);
                if (currSession != null) {
                    sessionList.remove(currSession);
                    currSession.close();
                }
            }
            logger.info("当前在线人数：{}", sessionPool.size());
        } catch (Exception e) {
            logger.error("关闭连接失败！", e);
        }
    }

    public static void sendMessage(String memberId, String message) {
        if (StringUtil.isBlank(memberId) || !sessionPool.containsKey(memberId)) return;

        sessionPool.computeIfAbsent(memberId, list -> new ArrayList<>()).forEach(session -> {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                logger.error("发送消息失败：{}", message, e);
            }
        });
    }
}
